<?php
// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 许可证远程验证：每次打开页面都请求远程服务
$domain = wp_parse_url(site_url(), PHP_URL_HOST);
$license_key = get_option('wp_spider_license_key', '');
$verify_url = get_option('wp_spider_license_verify_url', '');
$license_active = false;
$license_message = '';
$license_data = array();

if (!empty($license_key) && !empty($verify_url)) {
    $payload = array(
        'license_key' => $license_key,
        'domain' => $domain,
        'plugin' => 'wp-spider-monitor',
    );
    // 可选签名
    $secret = get_option('spider_license_shared_secret');
    $payload['ts'] = time();
    $payload['nonce'] = wp_generate_password(8, false);
    if (!empty($secret)) {
        ksort($payload);
        $payload['sig'] = hash_hmac('sha256', http_build_query($payload, '', '&', PHP_QUERY_RFC3986), $secret);
    }
    $resp = wp_remote_post($verify_url, array(
        'timeout' => 10,
        'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'),
        'body' => $payload
    ));
    if (!is_wp_error($resp)) {
        $code = wp_remote_retrieve_response_code($resp);
        $body = wp_remote_retrieve_body($resp);
        $data = json_decode(trim($body), true);
        if ($code === 200 && is_array($data) && !empty($data['success'])) {
            // 兼容多种返回：active/status
            $license_active = !empty($data['active']) || (!empty($data['status']) && $data['status'] === 'active');
            $license_message = $data['message'] ?? '';
            $license_data = $data;
        } else {
            $license_message = __('远程服务返回异常或非200响应', 'wp-spider-monitor');
        }
    } else {
        $license_message = $resp->get_error_message();
    }
}

// 处理表单提交
if (isset($_POST['submit']) && wp_verify_nonce($_POST['wp_spider_monitor_settings_nonce'], 'wp_spider_monitor_settings')) {
    $settings = array(
        'max_pages' => intval($_POST['max_pages']),
        'delay_between_requests' => floatval($_POST['delay_between_requests']),
        'user_agent' => sanitize_text_field($_POST['user_agent']),
        'timeout' => intval($_POST['timeout']),
        'follow_redirects' => isset($_POST['follow_redirects']),
        'check_external_links' => isset($_POST['check_external_links']),
        'auto_analyze_new_posts' => isset($_POST['auto_analyze_new_posts']),
        'cron_interval' => sanitize_text_field($_POST['cron_interval']),
        'email_notifications' => isset($_POST['email_notifications']),
        'notification_email' => sanitize_email($_POST['notification_email']),
        'interface_theme' => sanitize_text_field($_POST['interface_theme'])
    );
    
    update_option('wp_spider_monitor_settings', $settings);
    echo '<div class="notice notice-success"><p>设置已保存！</p></div>';
}

// 获取当前设置
$settings = get_option('wp_spider_monitor_settings', array());
$defaults = array(
    'max_pages' => 100,
    'delay_between_requests' => 1,
    'user_agent' => 'WordPress URL Spider/1.0',
    'timeout' => 30,
    'follow_redirects' => true,
    'check_external_links' => false,
    'auto_analyze_new_posts' => false,
    'cron_interval' => 'daily',
    'email_notifications' => false,
    'notification_email' => get_option('admin_email'),
    'interface_theme' => 'modern'
);

$settings = wp_parse_args($settings, $defaults);

// 主题名称映射
$theme_names = array(
    'modern' => '🎨 现代化主题',
    'classic' => '📊 经典主题',
    'minimal' => '⚡ 极简主题',
    'dark' => '🌙 暗黑主题',
    'colorful' => '🌈 多彩主题',
    'vibrant' => '🌈 活力彩虹',
    'cyberpunk' => '⚡ 赛博朋克',
    'nature' => '🌿 自然生态'
);
?>

<div class="wrap wp-spider-monitor-settings">
    <h1>蜘蛛监控设置</h1>
    
    <div id="theme-notification" class="notice" style="position: absolute; top: 10px; right: 10px; display: none;">主题已更新！</div>
    
    <form method="post" action="">
        <?php wp_nonce_field('wp_spider_monitor_settings', 'wp_spider_monitor_settings_nonce'); ?>
        
        <div class="wp-spider-monitor-settings-container">
            <!-- 基本设置 -->
            <div class="settings-section">
                <h2>基本设置</h2>
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="max_pages">最大分析页面数</label>
                        </th>
                        <td>
                            <input type="number" id="max_pages" name="max_pages" 
                                   value="<?php echo esc_attr($settings['max_pages']); ?>" 
                                   min="1" max="1000" class="small-text">
                            <p class="description">单次批量分析的最大页面数量</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="delay_between_requests">请求间隔（秒）</label>
                        </th>
                        <td>
                            <input type="number" id="delay_between_requests" name="delay_between_requests" 
                                   value="<?php echo esc_attr($settings['delay_between_requests']); ?>" 
                                   min="0.1" max="10" step="0.1" class="small-text">
                            <p class="description">请求之间的延迟时间，避免对目标服务器造成过大压力</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="user_agent">用户代理</label>
                        </th>
                        <td>
                            <input type="text" id="user_agent" name="user_agent" 
                                   value="<?php echo esc_attr($settings['user_agent']); ?>" 
                                   class="regular-text">
                            <p class="description">发送请求时使用的用户代理字符串</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="timeout">请求超时时间（秒）</label>
                        </th>
                        <td>
                            <input type="number" id="timeout" name="timeout" 
                                   value="<?php echo esc_attr($settings['timeout']); ?>" 
                                   min="5" max="300" class="small-text">
                            <p class="description">单个请求的超时时间</p>
                        </td>
                    </tr>
                </table>
            </div>
            
            <!-- 分析选项 -->
            <div class="settings-section">
                <h2>分析选项</h2>
                <table class="form-table">
                    <tr>
                        <th scope="row">重定向处理</th>
                        <td>
                            <label>
                                <input type="checkbox" name="follow_redirects" value="1" 
                                       <?php checked($settings['follow_redirects']); ?>>
                                自动跟随重定向
                            </label>
                            <p class="description">是否自动跟随HTTP重定向</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">外部链接检查</th>
                        <td>
                            <label>
                                <input type="checkbox" name="check_external_links" value="1" 
                                       <?php checked($settings['check_external_links']); ?>>
                                检查外部链接状态
                            </label>
                            <p class="description">检查页面中的外部链接是否有效（可能影响分析速度）</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">自动分析新文章</th>
                        <td>
                            <label>
                                <input type="checkbox" name="auto_analyze_new_posts" value="1" 
                                       <?php checked($settings['auto_analyze_new_posts']); ?>>
                                发布新文章时自动分析
                            </label>
                            <p class="description">当发布新文章时自动分析其URL</p>
                        </td>
                    </tr>
                </table>
            </div>
            
            <!-- 定时任务设置 -->
            <div class="settings-section">
                <h2>定时任务设置</h2>
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="cron_interval">定时分析间隔</label>
                        </th>
                        <td>
                            <select id="cron_interval" name="cron_interval">
                                <option value="disabled" <?php selected($settings['cron_interval'], 'disabled'); ?>>禁用</option>
                                <option value="hourly" <?php selected($settings['cron_interval'], 'hourly'); ?>>每小时</option>
                                <option value="twicedaily" <?php selected($settings['cron_interval'], 'twicedaily'); ?>>每12小时</option>
                                <option value="daily" <?php selected($settings['cron_interval'], 'daily'); ?>>每天</option>
                                <option value="weekly" <?php selected($settings['cron_interval'], 'weekly'); ?>>每周</option>
                            </select>
                            <p class="description">设置自动分析网站页面的频率</p>
                        </td>
                    </tr>
                </table>
            </div>
            
            <!-- 通知设置 -->
            <div class="settings-section">
                <h2>通知设置</h2>
                <table class="form-table">
                    <tr>
                        <th scope="row">邮件通知</th>
                        <td>
                            <label>
                                <input type="checkbox" name="email_notifications" value="1" 
                                       <?php checked($settings['email_notifications']); ?>>
                                启用邮件通知
                            </label>
                            <p class="description">分析完成或出现错误时发送邮件通知</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">
                            <label for="notification_email">通知邮箱</label>
                        </th>
                        <td>
                            <input type="email" id="notification_email" name="notification_email" 
                                   value="<?php echo esc_attr($settings['notification_email']); ?>" 
                                   class="regular-text">
                            <p class="description">接收通知的邮箱地址</p>
                        </td>
                    </tr>
                </table>
            </div>
            
            <!-- 界面设置 -->
            <div class="settings-section">
                <h2>界面设置</h2>
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="interface_theme">主题选择</label>
                        </th>
                        <td>
                            <select name="interface_theme" id="interface_theme">
                                <option value="modern" <?php selected($settings['interface_theme'], 'modern'); ?>>🎨 现代化主题</option>
                                <option value="classic" <?php selected($settings['interface_theme'], 'classic'); ?>>📊 经典主题</option>
                                <option value="minimal" <?php selected($settings['interface_theme'], 'minimal'); ?>>⚡ 极简主题</option>
                                <option value="dark" <?php selected($settings['interface_theme'], 'dark'); ?>>🌙 暗黑主题</option>
                                <option value="colorful" <?php selected($settings['interface_theme'], 'colorful'); ?>>🌈 多彩主题</option>
                                <option value="vibrant" <?php selected($settings['interface_theme'], 'vibrant'); ?>>🌈 活力彩虹</option>
                                <option value="cyberpunk" <?php selected($settings['interface_theme'], 'cyberpunk'); ?>>⚡ 赛博朋克</option>
                                <option value="nature" <?php selected($settings['interface_theme'], 'nature'); ?>>🌿 自然生态</option>
                            </select>
                            <p class="description">当前主题：<span id="current-theme-name">
                                <?php 
                                $themeNames = [
                                    'modern' => '🎨 现代化主题',
                                    'classic' => '📊 经典主题',
                                    'minimal' => '⚡ 极简主题',
                                    'dark' => '🌙 暗黑主题',
                                    'colorful' => '🌈 多彩主题',
                                    'vibrant' => '🌈 活力彩虹',
                                    'cyberpunk' => '⚡ 赛博朋克',
                                    'nature' => '🌿 自然生态'
                                ];
                                echo $themeNames[$settings['interface_theme']] ?? '🎨 现代化主题';
                                ?>
                            </span></p>
                            
                        </td>
                    </tr>
                </table>
            </div>
            
            <!-- 数据管理 -->
            <div class="settings-section">
                <h2>数据管理</h2>
                <table class="form-table">
                    <tr>
                        <th scope="row">清理数据</th>
                        <td>
                            <button type="button" class="button" id="clear-old-data">
                                清理30天前的数据
                            </button>
                            <p class="description">删除30天前的分析数据以节省空间</p>
                        </td>
                    </tr>
                    
                    <tr>
                        <th scope="row">重置设置</th>
                        <td>
                            <button type="button" class="button" id="reset-settings" style="color: #a00;">
                                重置为默认设置
                            </button>
                            <p class="description">将所有设置恢复为默认值</p>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
        
        <p class="submit">
            <input type="submit" name="submit" class="button-primary" value="保存设置">
        </p>
    </form>
    
    <!-- 系统信息 -->
    <div class="settings-section">
        <h2>系统信息</h2>
        <table class="form-table">
            <tr>
                <th scope="row">插件版本</th>
                <td><?php echo WP_SPIDER_MONITOR_VERSION; ?></td>
            </tr>
            <tr>
                <th scope="row">WordPress版本</th>
                <td><?php echo get_bloginfo('version'); ?></td>
            </tr>
            <tr>
                <th scope="row">PHP版本</th>
                <td><?php echo PHP_VERSION; ?></td>
            </tr>
            <tr>
                <th scope="row">数据库表状态</th>
                <td>
                    <?php
                    global $wpdb;
                    $visits_table = $wpdb->prefix . 'spider_visits';
                    $stats_table = $wpdb->prefix . 'spider_stats';
                    
                    $visits_exists = $wpdb->get_var("SHOW TABLES LIKE '$visits_table'") == $visits_table;
                    $stats_exists = $wpdb->get_var("SHOW TABLES LIKE '$stats_table'") == $stats_table;
                    
                    if ($visits_exists && $stats_exists) {
                        $visits_count = $wpdb->get_var("SELECT COUNT(*) FROM $visits_table");
                        $stats_count = $wpdb->get_var("SELECT COUNT(*) FROM $stats_table");
                        echo "✅ 正常 (访问记录: $visits_count 条, 统计数据: $stats_count 条)";
                    } else {
                        echo "❌ 数据库表不存在";
                        if (!$visits_exists) echo " (缺少访问记录表)";
                        if (!$stats_exists) echo " (缺少统计表)";
                    }
                    ?>
                </td>
            </tr>
            <tr>
                <th scope="row">内存限制</th>
                <td><?php echo ini_get('memory_limit'); ?></td>
            </tr>
            <tr>
                <th scope="row">最大执行时间</th>
                <td><?php echo ini_get('max_execution_time'); ?> 秒</td>
            </tr>
        </table>
    </div>
</div>

<style>
.wp-url-spider-settings-container {
    max-width: 800px;
}

.settings-section {
    background: #fff;
    border: 1px solid #ccd0d4;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
}

.settings-section h2 {
    margin-top: 0;
    color: #23282d;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.settings-section .form-table th {
    width: 200px;
    padding: 15px 10px 15px 0;
    vertical-align: top;
}

.settings-section .form-table td {
    padding: 15px 10px;
}

.settings-section .form-table input[type="checkbox"] {
    margin-right: 8px;
}

.settings-section .form-table .description {
    margin: 5px 0 0 0;
    color: #666;
    font-style: italic;
}

.button {
    margin-right: 10px;
}

#clear-old-data,
#reset-settings {
    margin-right: 10px;
}

/* 主题预览样式 */
.theme-preview-container {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.theme-preview {
    display: inline-block;
    width: 80px;
    height: 60px;
    border: 2px solid #ddd;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    overflow: hidden;
    position: relative;
}

.theme-preview:hover {
    border-color: #0073aa;
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 115, 170, 0.15);
}

.theme-preview.hover-preview {
    border-color: #0073aa;
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(0, 115, 170, 0.15);
}

.theme-preview.active {
    border-color: #0073aa;
    box-shadow: 0 0 0 2px rgba(0, 115, 170, 0.2);
}

.preview-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    text-align: center;
}

.preview-color {
    width: 100%;
    height: 30px;
    margin-bottom: 4px;
    border-radius: 4px 4px 0 0;
}

.preview-content span {
    font-size: 10px;
    color: #666;
    line-height: 1.2;
}

.notice {
    padding: 10px;
    background-color: #fff;
    border-left: 4px solid #46b450;
    box-shadow: 0 1px 1px rgba(0,0,0,.04);
}

@media (max-width: 768px) {
    .settings-section .form-table th,
    .settings-section .form-table td {
        display: block;
        width: 100%;
        padding: 10px 0;
    }
    
    .settings-section .form-table th {
        border-bottom: none;
        padding-bottom: 5px;
    }
    
    .theme-preview-container {
        justify-content: center;
    }
    
    .theme-preview {
        width: 70px;
        height: 50px;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    // 设置当前主题的激活状态
    const currentTheme = '<?php echo $settings['interface_theme'] ?? 'modern'; ?>';
    $(`.theme-preview-${currentTheme}`).addClass('active');
    
    // 主题预览点击事件
    $(document).on('click', '.theme-preview', function() {
        const theme = $(this).data('theme');
        $('#interface_theme').val(theme);
        
        // 更新当前主题显示
        const themeNames = {
            'modern': '🎨 现代化主题',
            'classic': '📊 经典主题',
            'minimal': '⚡ 极简主题',
            'dark': '🌙 暗黑主题',
            'colorful': '🌈 多彩主题',
            'vibrant': '🌈 活力彩虹',
            'cyberpunk': '⚡ 赛博朋克',
            'nature': '🌿 自然生态'
        };
        $('#current-theme-name').text(themeNames[theme] || '现代化主题');
        
        // 更新激活状态
        $('.theme-preview').removeClass('active');
        $(this).addClass('active');
        
        // 应用主题样式
        if (typeof ThemeManager !== 'undefined') {
            ThemeManager.applyTheme(theme);
        }
        
        // 显示通知
        $('#theme-notification').fadeIn().delay(2000).fadeOut();
    });
    
    // 下拉菜单改变事件
    $('#interface_theme').on('change', function() {
        const theme = $(this).val();
        const themeNames = {
            'modern': '🎨 现代化主题',
            'classic': '📊 经典主题',
            'minimal': '⚡ 极简主题',
            'dark': '🌙 暗黑主题',
            'colorful': '🌈 多彩主题',
            'vibrant': '🌈 活力彩虹',
            'cyberpunk': '⚡ 赛博朋克',
            'nature': '🌿 自然生态'
        };
        
        // 更新当前主题显示
        $('#current-theme-name').text(themeNames[theme] || '现代化主题');
        
        // 更新预览激活状态
        $('.theme-preview').removeClass('active');
        $(`.theme-preview-${theme}`).addClass('active');
        
        // 应用主题样式
        if (typeof ThemeManager !== 'undefined') {
            ThemeManager.applyTheme(theme);
        }
        
        // 显示通知
        $('#theme-notification').fadeIn().delay(2000).fadeOut();
    });
    
    // 清理旧数据
    $('#clear-old-data').on('click', function() {
        if (confirm('确定要清理30天前的数据吗？此操作不可撤销！')) {
            $.post(ajaxurl, {
                action: 'spider_clear_old_visits',
                nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
            }, function(response) {
                if (response.success) {
                    alert('数据清理完成！删除了 ' + response.data.deleted + ' 条记录。');
                } else {
                    alert('清理失败：' + response.data);
                }
            });
        }
    });
    
    // 重置设置
    $('#reset-settings').on('click', function() {
        if (confirm('确定要重置所有设置为默认值吗？此操作不可撤销！')) {
            $.post(ajaxurl, {
                action: 'spider_reset_settings',
                nonce: '<?php echo wp_create_nonce('wp_spider_monitor_nonce'); ?>'
            }, function(response) {
                if (response.success) {
                    alert('设置已重置！页面将刷新。');
                    location.reload();
                } else {
                    alert('重置失败：' + response.data);
                }
            });
        }
    });
});
</script>

<!-- 插件内部底部标志 -->
<div class="spider-footer">
    <div class="spider-footer-content">
        <a href="https://zibovip.top" target="_blank" class="spider-footer-logo">
            <span class="logo-text">小Z</span>
        </a>
    </div>
</div>